<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="dns-prefetch" href="https://cdnjs.cloudflare.com">
  <title>交通灯问题</title>
  <style>
    .light-container {
      display: flex;
      width: 120px;
      margin: 0 auto;
      justify-content: space-around;
      align-items:  center;
    }
    .light {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background-color: #ccc;
    }
    .tarffice-light.green .light:first-child {
      background-color: #0f0;
    }
    .tarffice-light.yellow .light:nth-child(2) {
      background-color: #eeff00;
    }
    .tarffice-light.red .light:nth-child(3){
      background-color: #f00;
    }
    .time {
      padding-top: 10px;
      font-size: 32px;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="tarffice-light">
    <div class="light-container">
      <div class="light"></div>
      <div class="light"></div>
      <div class="light"></div>
    </div>
    <div class="time">90</div>
  </div>
  <pre>
    <code class="language-javascript  code" >
    </code>
  </pre>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/javascript.min.js"></script>
  <script></script>
  <script type="module" class="s1">
    import { TrafficLight } from './TrafficLight.js'
    const time = document.querySelector('.time');
    const trafficeDom = document.querySelector('.tarffice-light');

    let frame = undefined;
    // 问询模式
    const light = new TrafficLight({
      red: 12,
      yellow: 5,
      green: 8,
      initial: 'red'
    })
    // const current = light.getCurrentLight()
    // current.color;  // 当前的颜色
    // current.remain; // 当前颜色的剩余时间

    function ref() {
      frame = requestAnimationFrame(() => {
        ref()
        const current = light.getCurrentLight()
        time.textContent = current.remain;
        trafficeDom.className = `tarffice-light ${current.color}`
        console.log(current.color, current.remain)

      })
    }
    ref()

    // 临时添加
    document.addEventListener('visibilitychange', function() {
      if (document.visibilityState ==='hidden') {
        cancelAnimationFrame(frame)
        console.log('页面失活，交通灯暂停')
      } else {
        ref()
        console.log('页面激活，交通灯开始')
      }
      
    })
  </script>
  <script>
   
    window.onload = function () {
      const codeDom = document.querySelector('.code');
      const s1 =document.querySelector('.s1');
      codeDom.textContent = s1.innerText
      hljs.highlightAll();
    
    }
  </script>
</body>
</html>